package com.zhengke.controller;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.zhengke.common.util.tools.CommonUtil;
import com.zhengke.common.util.tools.DateUtil;
import com.zhengke.common.util.tools.LoadProperties;
import com.zhengke.pojo.SysDictionaryItem;
import com.zhengke.pojo.TvUserOpera;
import com.zhengke.pojo.archie.CurrentUser;
import com.zhengke.pojo.archie.OrderPagination;
import com.zhengke.service.IDiscountService;
import com.zhengke.service.ISaleService;


/****************************
 * 	创建时间  2020年1月16日 下午3:50:20
 *	项目名称 tvmallws Maven Webapp
 * 	@author 刘荣乾
 *	@version 1.0 
 *	文件名称：SalesController.java
 *	类说明：
 ****************************/

@Controller
public class SalesController extends OrderPagination{

	@Autowired
	private IDiscountService discountService;
	@Autowired
	private ISaleService service;
	
	
	/**
	 * 到销售排行列表页面
	 * @return
	 */
	@RequestMapping("toSalesList")
	public String toSalesList(HttpServletResponse response,HttpServletRequest request,ModelMap model) {
		
		CurrentUser user = getCurrentUser(request, response);
		TvUserOpera tvUserOpera = new TvUserOpera();
		tvUserOpera.setId(CommonUtil.createUUID());
		tvUserOpera.setUserId(Integer.parseInt(user.getTvnNo()));
		tvUserOpera.setUserName(user.getUserName());
		tvUserOpera.setType(1);
		tvUserOpera.setTime(DateUtil.currentTime());
		tvUserOpera.setText("销售排行");
		discountService.insertSelective(tvUserOpera);
		model.put("tmp", new Date());
		
		return "tv/sales/salesList";
		
	}

	/**
	 * 销售排行商品列表
	 */
	@RequestMapping("salesData")
	@ResponseBody
	public void salesData(HttpServletResponse response,HttpServletRequest request,ModelMap model) {
		
		CurrentUser user = getCurrentUser(request, response);
		
		String pointId = user.getStationId();//服务点ID
		try {
			List<SysDictionaryItem> dicItem = service.findDicItem();
			List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
			if (dicItem.size()>0) {
				if (dicItem.get(0).getParamValue().equals("按月销量")) {
					list=service.querySalesList(pointId, "1");
				}
				else if (dicItem.get(0).getParamValue().equals("按周销量")) {
					list=service.querySalesList(pointId, "2");
				}
//				else if (dicItem.get(0).getParamValue().equals("手工设置")) {
//					List<Map<String, Object>> list2 = service.querySalesList2(pointId);
//					List<Map<String, Object>> list3 = service.querySalesList3();
//			
//					if (list3.size()==0) {
//						list = list2;
//					}else {
//						List<Map<String	, Object>> list4 = new ArrayList<Map<String,Object>>();
//						for (int i = 0; i < list3.size(); i++) {
//							for (int j = 0; j < list2.size(); j++) {
//								if (list3.get(i).get("goods_id").toString().equals(list2.get(j).get("goods_common_id").toString())) {
//									list4.add(list2.get(j));
//									list2.remove(j);
//								}
//							}
//						}
//						for (int i = 0; i < list2.size(); i++) {
//							list4.add(list2.get(i));
//						}
//						list = list4;
//						
//					}
//				}
				
				else 
					list = service.querySalesList(pointId, "0");
				
			}else {
				list = service.querySalesList(pointId, "0");
			}
			List<Map<String, Object>> rtnList = new ArrayList<Map<String,Object>>();
			String notFoundPic = LoadProperties.findValue("losePicForList");
			for(Map<String,Object> obj:list) {
				Map<String, Object> temp = new HashMap<String, Object>();
				String picPath = obj.get("thumb_picPath")==null?"":obj.get("thumb_picPath").toString();
				if (picPath==null||"".equals(picPath)) {
					picPath = request.getSession().getServletContext().getRealPath(notFoundPic);
				}else {
					
					String begin = picPath.substring(0,4);
					if ("http".equals(begin)) {
						try {
							URL url = new URL(picPath);
							URLConnection uc = url.openConnection();
							//打开的连接读取数据流
							InputStream in = uc.getInputStream();
						} catch (Exception e) {
							// TODO: handle exception
							System.err.println("没有");
							picPath =  request.getSession().getServletContext().getRealPath(notFoundPic);
						}
					}else {
					File f = new File(picPath);
					if (!f.exists()) {
						picPath = request.getSession().getServletContext().getRealPath(notFoundPic);
					}
						
					}
				}
				
				temp.put("commonGoodsId", obj.get("goods_common_id")==null?"":obj.get("goods_common_id").toString());
				temp.put("picPath",picPath);
				temp.put("goodsName",obj.get("goods_name")==null?"":obj.get("goods_name").toString());
				temp.put("goodsPromotionPrice",obj.get("common_price")==null?"":obj.get("common_price").toString());
				temp.put("type",obj.get("goods_type").toString());
				rtnList.add(temp);
			}
			
			response.setCharacterEncoding("utf-8");
			response.setHeader("Pragma","No-cache"); 
			response.setHeader("Cache-Control","no-cache"); 
			response.setDateHeader("Expires", 0);  
			response.getWriter().print("var dataList="+JSONArray.toJSON(rtnList));	
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		
	}
	
	/**
	 * 到商品详情页面
	 * @return
	 */
	@RequestMapping("toSalesGoodsDetail")
	public String togoodsDetail(String goodsId,String orderNumber,String type,String pageTitle,ModelMap model,HttpServletRequest request,HttpServletResponse response) {
		//商品类型，“5”打包品，“1”打折品,"0"正品,"2"体验品,"3"积分兑换商品,"7"可兑换打包品，
		CurrentUser user = getCurrentUser(request, response);
		System.err.println(type+"==================================================================================");
		System.err.println(goodsId+"==================================================================================");
		
		model.put("pageTitle", pageTitle);
		model.put("tmp", new Date());
		
		String i = discountService.queryParamValueByItemId("00010001");
		String[] str = i.split(":");
		double a = Double.parseDouble(str[0]);
		double b = Double.parseDouble(str[1]);
		try{
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			double commonPrice = 0.0d;
			if("1".equals(type)||"2".equals(type)||"3".equals(type)||"7".equals(type)){
				list = discountService.findGoodsDetail(goodsId);
			}else{
				list = discountService.findGoodsDetail2(goodsId);
				if("5".equals(type)){
					if(list.size()>0){
						List<Map<String, Object>> list3 = discountService.findBaleGoods(list.get(0).get("").toString());
						for(Map<String, Object> map:list3){
							commonPrice+=(Double.parseDouble(map.get("goods_price").toString())*Integer.parseInt(map.get("goods_num").toString()));
						}
					}
				}
			}
			
			for(Map<String, Object> obj:list){
				String infoPicPath = obj.get("info_picPath").toString();
				String notInfoPic =  LoadProperties.findValue("loseInfoPicForGoodsDetail");
				if(infoPicPath==null||"".equals(infoPicPath))
					infoPicPath = request.getSession().getServletContext().getRealPath(notInfoPic);
				else{
					File f = new File(infoPicPath);
					if(!f.exists())
						infoPicPath = request.getSession().getServletContext().getRealPath(notInfoPic);
				}
				
				List<String> rtnList = new ArrayList<String>();
				
				if(obj.get("picPath1")!=null&&!"".equals(obj.get("picPath1")))
					rtnList.add(obj.get("picPath1").toString());
				if(obj.get("picPath2")!=null&&!"".equals(obj.get("picPath2")))
					rtnList.add(obj.get("picPath2").toString());
				if(obj.get("picPath3")!=null&&!"".equals(obj.get("picPath3")))
					rtnList.add(obj.get("picPath3").toString());
				if(obj.get("picPath4")!=null&&!"".equals(obj.get("picPath4")))
					rtnList.add(obj.get("picPath4").toString());
				if(obj.get("picPath5")!=null&&!"".equals(obj.get("picPath5")))
					rtnList.add(obj.get("picPath5").toString());
				
				if(rtnList.size()==0){
					String notFoundPic =  LoadProperties.findValue("losePicForGoods");
					rtnList.add(request.getSession().getServletContext().getRealPath(notFoundPic));
				}
				if("1".equals(type)){
					model.put("commonPrice", "￥"+obj.get("common_price"));//原价
				}
				if("5".equals(type)){
					model.put("commonPrice", "￥"+commonPrice);//原价
				}
			
				if("3".equals(type)||"7".equals(type)){
					String goodsPrice  = obj.get("goods_price")==null?"":obj.get("goods_price").toString();
					double d = Double.parseDouble(goodsPrice)*(a/b);
					model.put("commonPrice", d);//所需兑换积分
				}
				
				String shippingFee  = obj.get("shipping_fee")==null?"":obj.get("shipping_fee").toString();
				double s = Double.parseDouble(shippingFee)*(a/b);
				model.put("shippingFee", s);//运费
				
				TvUserOpera tvUserOpera = new TvUserOpera();
				tvUserOpera.setId(CommonUtil.createUUID());
				tvUserOpera.setUserId(Integer.parseInt(user.getTvnNo()));
				tvUserOpera.setUserName(user.getUserName());
				tvUserOpera.setType(4);
				tvUserOpera.setTime(DateUtil.currentTime());
				tvUserOpera.setText(obj.get("goods_name").toString());
				discountService.insertSelective(tvUserOpera);
	
				model.put("goodsId", goodsId);
				model.put("picList",rtnList);
				model.put("picList", rtnList);
				model.put("goodsName", obj.get("goods_name"));
//				model.put("goodsPrice", "￥"+obj.get("goods_price"));//打折价
				model.put("goodsPrice", 12);//打折价
				model.put("deliveryWay", "门店自提");//收货方式
				model.put("supplierName", obj.get("supplier_name"));//供应商名称
				model.put("supplierId", obj.get("supplier_id"));//供应商id
				model.put("infoPicPath", infoPicPath);//介绍图片
				model.put("awardedIntegral", obj.get("awarded_integral"));//赠送积分
				model.put("specifications", obj.get("specifications"));//商品规格
			}
			if(orderNumber==null||"".equals(orderNumber))
				model.put("orderNumber", 1);
			else
				model.put("orderNumber", orderNumber);
			
			//图片查询滚动时间
				model.put("time", "1000");//轮播图片滚动时间
			if("0".equals(type)||"2".equals(type)){
				model.put("show", "0");//显示类型
			}else{
				model.put("show", "1");//显示类型
			}
			model.put("type", type);//商品类型
			
			
		}catch(Exception e){
			e.printStackTrace();
		}		
		return "tv/sales/GoodsDetails";
	}
	

}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
